#include<iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
typedef websocketpp::server<websocketpp::config::asio> webserve_t;/*相当于把server模板化了这样我们可以访问它的父类的类型*/
/*
typedef lib::function<void(connection_hdl)> open_handler;
 typedef lib::function<void(connection_hdl)> close_handler;
 typedef lib::function<void(connection_hdl)> http_handler;
 typedef lib::function<void(connection_hdl,message_ptr)>
*/
//http请求的回调函数
void http_callback(webserve_t *srv, websocketpp::connection_hdl hdl) 
{
    /*获取connection_hdl 对应连接的connection_ptr*/
    //connection_ptr get_con_from_hdl(connection_hdl hdl);
    //获取对应客户端的连接的指针
    webserve_t ::connection_ptr conn=srv->get_con_from_hdl(hdl);
    //获取消息主体
    std::cout << "body: " << conn->get_request_body() << std::endl; 
    websocketpp::http::parser::request req=conn->get_request();
    std::cout << "method: " << req.get_method() << std::endl;
    std::cout << "uri: " << req.get_uri() << std::endl;


    std::string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type", "text/html");
    conn->set_status(websocketpp::http::status_code::ok);

}
void wsopen_callback(webserve_t*srv, websocketpp::connection_hdl hdl) 
{
     std::cout << "websocket握手成功！！\n";
}
void wsclose_callback(webserve_t*srv, websocketpp::connection_hdl hdl) 
{
    std::cout << "websocket连接断开！！\n";
}
void wsmsg_callback(webserve_t *srv, websocketpp::connection_hdl hdl, webserve_t::message_ptr msg) 
{
   webserve_t::connection_ptr conn = srv->get_con_from_hdl(hdl);
   std::cout << "wsmsg: " << msg->get_payload() << std::endl;
    std::string rsp = "client say: " + msg->get_payload();
    //给客户端发宋处理后的消息
    conn->send(rsp, websocketpp::frame::opcode::text);
}
int main()
{
    //1.建里serve对象 serve继承endpoint
    webserve_t wbserve;
    //2.设置websocket的日志
    wbserve.set_access_channels(websocketpp::log::alevel::none);
    //3.初始化asio中的调度器 
    wbserve.init_asio();
    wbserve.set_reuse_addr(true);
    //4.设置回调函数

     /*websocket握⼿成功回调处理函数*/
    wbserve.set_open_handler(std::bind(wsopen_callback,&wbserve,std::placeholders::_1));
    /*websocket连接关闭回调处理函数*/
    wbserve.set_close_handler(std::bind(wsclose_callback,&wbserve,std::placeholders::_1));
    /*websocket消息回调处理函数*/
    wbserve.set_message_handler(std::bind(wsmsg_callback,&wbserve,std::placeholders::_1, std::placeholders::_2));
    /*http请求回调处理函数*/
    wbserve.set_http_handler(std::bind(http_callback,&wbserve,std::placeholders::_1));

    //5.设置服务器为监听的端口号
    wbserve.listen(8080);


    //6.获取和客户端的连接
    wbserve.start_accept();


    //7..启动服务器
    wbserve.run();
   
    return 0;
}